/*
 * @Author: 高富强
 * @Email: 875627570@qq.com
 * @Date: 2020-06-04 09:06:42
 * @Last Modified by: 高富强
 * @Last Modified time: 2020-06-04 11:13:14
 * @Description: 班级页面 - 班级信息页
 */

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/model_data/classinfo/classinfo.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_sfsymbols/flutter_sfsymbols.dart';
import 'package:flutter_code_framework/route/route_transition.dart';
import 'package:flutter_code_framework/widgets/x_dialog_page.dart';
import 'package:flutter_code_framework/pages/class_room_page.dart';
import 'package:flutter_code_framework/base/base_main_tabbar.dart';

class ClassInfoPage extends BaseWidget {
  String classId;
  ClassInfoPage({Key key,this.classId}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _ClassInfoPageState(classId:this.classId);
  }
}

class _ClassInfoPageState extends BaseWidgetState<ClassInfoPage> {
  String classId;
  String className=" ";
  bool isManager=false;
  bool isInClass=false;
  int countflag=1;//加载进度是否显示用
  List<Object> studentList = [null];
  ScrollController _controller = ScrollController();

  _ClassInfoPageState({Key key,this.classId}) {  }

  @override
  Widget buildWidget(BuildContext context) {
    bool isEmpty=false;
    if(studentList.length==1||studentList==[null] )
    {
      isEmpty=true;
    }
    return
          ListView(children: <Widget>[

                                SizedBox(height: 37),
                                Container(
                                  margin:EdgeInsets.only(left:24,right: 24),
                                    child:Row(
                                      //mainAxisAlignment: MainAxisAlignment.start,
                                        children: <Widget>[
                                          Expanded(

                                                    child:Text(className,
                                                        overflow: TextOverflow.ellipsis,
                                                        style: TextStyle(color:
                                                        Theme.of(context).primaryTextTheme.headline1.color
                                                        //Colors.black
                                                            ,
                                                            fontSize: 28.0)),
                                          ),
                                          Container(
                                            color:  Theme.of(context).backgroundColor
                                            //Colors.white
                                            ,
                                            child: Align(
                                                alignment: Alignment.centerLeft,
                                                child:Container(margin: EdgeInsets.only(left:10.0),
                                                  child:Icon(SFSymbols.person_2_square_stack_fill,size: 28,
                                                    color:
                                                    Theme.of(context).primaryColor
                                                    //Color.fromRGBO(107,165,147,1)
                                                    ,
                                                  ),
                                                )),
                                          ),
                                        ]),),
                                SizedBox( height: 16),
                                Container(
                                  //margin:EdgeInsets.only(left:24,right: 24),
                                  child:getStudentListView(context),
                                ),
                            ]
          );


  }

  Widget getStudentListView(BuildContext context) {
    Widget mainWidget;
    //默认空数据状态
    if ( studentList == [null]||studentList.length==1) {
      if(countflag==1) {
        mainWidget = Center(
          child: CircularProgressIndicator(),
        );
      }
      else{
        mainWidget = Center(
          child:Text(''),
        );
      }
    } else {
      // RefreshIndicator为ListView增加了下拉刷新能力，onRefresh参数传入一个方法，在下拉刷新时调用
      mainWidget =  ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        scrollDirection: Axis.vertical,
        itemCount: studentList.length,
        itemBuilder: (bcontext, index) =>
            _renderClassRow(index),
        controller: _controller,
        // physics: AlwaysScrollableScrollPhysics(),

      );
    }
    return mainWidget;
  }

  //初始化项目结构
  Widget _renderClassRow(int index) {
    Widget itemWidget;
    if (studentList[index] == null) {
      if (studentList.length - 1 == pageNum * curPage) {
        //加载更多
        itemWidget = Container(
            padding: const EdgeInsets.all(16.0),
            alignment: Alignment.center,
            child: SizedBox(
                width: 24.0,
                height: 24.0,
                child: CircularProgressIndicator(strokeWidth: 2.0)));
      } else {
        //到头了
        /*return Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(16.0),
            child: Text(
              "----我是有底线的-----",
              style: TextStyle(color: Colors.grey),
            ));*/
      }
    } else {
      itemWidget = Row(
        children: <Widget>[
          Expanded(
            child: getItemWidet(index),
          ),
        ],
      );
    }
    return InkWell(
      child: Padding(
        padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
        child: itemWidget,
      ),
      onTap: () {
        listViewItemFunction(index);
      },
    );
  }
  @override
  Widget getItemWidet(int index) {
    StudentList model = studentList[index];
    String studentId=model.id;

    bool isIn=false;
    bool isPizhun=false;

    if(isManager) {
      if (model.state == '已加入') {
        isIn = true;
      }
      else
        {
          isPizhun=true;
        }
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[

          SizedBox(height:23),
          Container(
            height:25,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
              Container(
                  color:
                  Theme.of(context).backgroundColor
                  ,
                  child:Text('${model.name}',style: TextStyle(
                      color:
                      Theme.of(context).primaryTextTheme.caption.color
                      ,
                      fontSize: 18.0))),
           Row(children: <Widget>[

                  isIn?  OutlineButton(

                    borderSide:new BorderSide(color: Theme.of(context).primaryTextTheme.headline6.color),
                    color: Theme.of(context).primaryTextTheme.button.color,
                    child:
                    new Text('重置密码',style: TextStyle(color: Theme.of(context).primaryTextTheme.headline6.color
                        //Colors.white
                        ,fontSize: 12.0))
                    ,
                    onPressed: () {
                      G.showToastDialog(context,
                          "确定要重置此学生的密码吗",
                          title: "提示",  callBack: () {
                          reset(studentId);
                        });
                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(35) //设置圆角
                    ),
                  ):Text(''),
                  isIn?Text(''):SizedBox(width: 9,),
                  isManager?SizedBox(width: 9,):Text(''),
                  isManager?FlatButton(
                    //minWidth: 70,
                    color:
                    Theme.of(context).accentColor
                    //Color.fromRGBO(237,122,108,1)
                    ,
                    child: new Text('移除',style: TextStyle(color: Theme.of(context).primaryTextTheme.button.color
                        //Colors.white
                        ,fontSize: 12.0)),
                    onPressed: () {
                      G.showToastDialog(context,
                          "确定要移除此学生吗",
                          title: "提示",  callBack: () {
                            delete(studentId);
                          });

                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(35) //设置圆角
                    ),
                  ):Text(''),
                  isPizhun?SizedBox(width: 9,):Text(''),
                  isPizhun?FlatButton(
                    //minWidth: 70,
                    color:
                    Theme.of(context).primaryColor
                    //Color.fromRGBO(107,165,147,1)
                    ,
                    child: new Text('批准',style: TextStyle(color: Theme.of(context).primaryTextTheme.button.color,fontSize: 12.0)),
                    onPressed: () {
                      G.showToastDialog(context,
                          "确定要批准此学生吗",
                          title: "提示",  callBack: () {
                            examine(studentId);
                          });


                    },
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(35) //设置圆角
                    ),
                  ):Text(''),


                ],
           ),


          ],),),
          SizedBox(height:22),
      ],
    );
  }
  loadData() async {
    var rs =await G.req.classData.getClassInfo(classId:classId);
    setState(() {
      isManager=rs.data["isManager"];
      isInClass=rs.data["isIn"];
      className=rs.data["name"].toString();
      studentList.addAll(rs.data["studentList"].map((e) => StudentList.fromJson(e)).toList());
      countflag++;
    });
  }
//退出
  exit() async {
    var rs =await G.req.classData.exit(classId:classId,operation: 'exit');
    if (rs.data['isOk'] == true) {
      //弹出'退出成功'，当前页面关闭
      showNormalToast(
        '退出成功',
      );
      //关闭当前页跳转到我的班级页面
      RouteTransition(BaseMainTabbarPage())
          .pushAndRemoveUntilTransRoute(context);

    }
  }
//解散
  dissolve() async {
    var rs =await G.req.classData.dissolve(classId:classId,operation: 'dissolve');
    if (rs.data['isOk'] == true) {
      //弹出'退出成功'，当前页面关闭
      showNormalToast(
        '解散成功',
      );
      //关闭当前页跳转到我的班级页面
      RouteTransition(BaseMainTabbarPage())
          .pushAndRemoveUntilTransRoute(context);
    }
  }
  //重置密码
  reset(String studentId) async {
    var rs =await G.req.classData.reset(classId:classId,operation: 'reset',studentId:studentId);
    if (rs.data['isOk'] == true) {
      //弹出'退出成功'，当前页面关闭
      showNormalToast(
        '重置密码成功',
      );
      //关闭当前页跳转到班级信息页
      //Navigator.pop(context);
    }
  }
  //移除
  delete(String studentId) async {
    var rs =await G.req.classData.delete(classId:classId,operation: 'delete',studentId:studentId);
    if (rs.data['isOk'] == true) {
      //弹出'退出成功'，当前页面关闭
      showNormalToast(
        '移除成功',
      );
      //关闭当前页跳转到班级信息页

      //Navigator.pop(context);
      RouteTransition(ClassInfoPage(classId:this.classId))
          .pushReplacementRoute(context);
    }
  }
  //批准
  examine(String studentId) async {
    print('批准班级id:'+classId);
    var rs =await G.req.classData.examine(classId:classId,operation: 'examine',studentId:studentId);
    if (rs.data['isOk'] == true) {
      //弹出'退出成功'，当前页面关闭
      showNormalToast(
        '批准成功',
      );
      //关闭当前页跳转到班级信息页
      //Navigator.pop(context);
      RouteTransition(ClassInfoPage(classId:this.classId))
          .pushReplacementRoute(context);
    }
  }
  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  void onCreate() {
    // log("onCreate");
    setAppTopNavBarVisible(true);
    setTopNavLeftIcon(SFSymbols.xmark);
  }

  @override
  void onPause() {
    // log('onPause');
  }

  @override
  void onResume() {
    // log("onResume");
  }
  @override
  Widget getTopNavRightWidget(BuildContext _contextBaseFunction) {
    return
      GestureDetector(
        child: new Text(isInClass?isManager?'解散班级':'退出班级':'',style: TextStyle(color:Theme.of(context).primaryColor,fontSize: 14.0)),
        onTap: () {
          if(isManager)
          {
            if(studentList.length>1)//有学生
                {
              G.showToastDialog(context,
                  "您确定要解散本班级？解散后您可以在历史班级查看班级空间信息。",
                  title: "提示",  callBack: () {
                    dissolve();
                  });

            }
            else//无学生
                {
              G.showToastDialog(context,
                  "您确定要解散本班级？",
                  title: "提示",  callBack: () {
                    dissolve();
                  });
            }
          }
          else
          {
            G.showToastDialog(context,
                "您确定要退出本班级？",
                title: "提示",  callBack: () {
                  exit();
                });

          }
        },
      )

      ;
  }
}
